package com.credithc.customers.dataservice.service.impl;

import com.credithc.baseserv.core.utils.UUIDUtils;
import com.credithc.customers.base.constants.CustomerConstants;
import com.credithc.customers.base.mapper.CustomerProductMapper;
import com.credithc.customers.base.mapper.CustomerRelationInfoMapper;
import com.credithc.customers.base.po.CustomerRelationInfoPo;
import com.credithc.customers.dataservice.Thread.OldDataThreadPoolExecutor;
import com.credithc.customers.dataservice.constants.SyncTypeEnum;
import com.credithc.customers.dataservice.mapper.BXHX.ProductMapper;
import com.credithc.customers.dataservice.mapper.BXHX.SalePolicyMapper;
import com.credithc.customers.dataservice.mapper.BXHX.SalePolicyProMapper;
import com.credithc.customers.dataservice.mapper.BXHX.YztSyncUserMapper;
import com.credithc.customers.dataservice.po.BXHXSalePolicyProPO;
import com.credithc.customers.dataservice.po.BxhxYztPO;
import com.credithc.customers.dataservice.po.HXBXPolicyPO;
import com.credithc.customers.dataservice.po.HXBXProductPO;
import com.credithc.customers.dataservice.ro.CustomerAccountInfoRo;
import com.credithc.customers.dataservice.ro.CustomerProductInfoRo;
import com.credithc.customers.dataservice.ro.ProductInfoRo;
import com.credithc.customers.dataservice.service.OldBXHXDataService;
import com.credithc.customers.dataservice.service.SyncDataService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.atomic.AtomicReference;

@Service
@Slf4j
public class OldBXHXDataServiceImpl implements OldBXHXDataService {
    @Autowired
    private SalePolicyMapper salePolicyMapper;
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private SalePolicyProMapper salePolicyProMapper;
    @Autowired
    private YztSyncUserMapper yztSyncUserMapper;
    @Autowired
    private OldDataThreadPoolExecutor oldDataThreadPoolExecutor;
    @Autowired
    private SyncDataService syncDataService;
    @Autowired
    private CustomerRelationInfoMapper customerRelationInfoMapper;
    @Override
    public void product(Integer start) {
        boolean f =true;
        Long num = null;
        if (start != null && start >0) {
            num = Long.valueOf(start);
        }else{
            num = productMapper.queryProductMaxId();
        }
        if (num == null){
            return;
        }
        AtomicReference<Long> vernier = new AtomicReference<>( num+10001);
        ExecutorService e = oldDataThreadPoolExecutor.getCustomThreadPoolExecutor();
        while (f) {
            e.execute(() -> {
                try {
                    if (vernier.get()>0){
                        vernier.set(vernier.get()-10000);
                    }
                    Example example = new Example(HXBXProductPO.class);
                    Example.Criteria criteria = example.createCriteria();
                    criteria.andBetween("id",vernier.get()-10000,vernier.get());
                    List<HXBXProductPO> hxbxProductPOS = productMapper.selectByExample(example);
                    if (hxbxProductPOS.size() > 0) {
                        bulidProduct(hxbxProductPOS);
                    }
                } catch (Exception e1) {
                    log.error(e1.getMessage());
                }
            });
            f = OldHyrDataServiceImpl.exit(f, vernier, e);
        }
    }

    private void bulidProduct(List<HXBXProductPO> hxbxProductPOS) {
        for (HXBXProductPO h:hxbxProductPOS) {
            ProductInfoRo productInfoRo = new ProductInfoRo();
            String eventType = SyncTypeEnum.NEW.getValue();
            productInfoRo.setSyncType(eventType);
            productInfoRo.setDatabaseName("baoxian");
            productInfoRo.setTableName("pro_info");
            productInfoRo.setProductChannel("BXHX");
            productInfoRo.setSubSystemSign("BXHX");
            productInfoRo.setSystemSign("BX");
            productInfoRo.setProductType(3+"");
            productInfoRo.setProductNo(h.getId()+"");
            productInfoRo.setTableKey(h.getId()+"");
            productInfoRo.setProductName(h.getProName());
            productInfoRo.setProductCreateTime(new Timestamp(Long.valueOf(h.getCreateTime())*1000));
            syncDataService.syncProduct(productInfoRo);
        }
    }

    @Override
    public void data(Integer start) {
        boolean f =true;
        Long num = null;
        if (start != null && start>0) {
            num = Long.valueOf(start);
        }else{
            num = salePolicyMapper.queryOrderMaxId();
        }
        if (num == null){
            return;
        }
        AtomicReference<Long> vernier = new AtomicReference<>( num+10001);
        ExecutorService e = oldDataThreadPoolExecutor.getCustomThreadPoolExecutor();
        while (f) {
            e.execute(() -> {
                try {
                    if (vernier.get()>0){
                        vernier.set(vernier.get()-10000);
                    }
                    Example example = new Example(HXBXPolicyPO.class);
                    Example.Criteria criteria = example.createCriteria();
                    criteria.andBetween("id",vernier.get()-10000,vernier.get());
                    List<HXBXPolicyPO> bdbInSurePOS = salePolicyMapper.selectByExample(example);
                    if (bdbInSurePOS.size() > 0) {
                        bulidOrder(bdbInSurePOS);
                    }
                } catch (Exception e1) {
                    e1.printStackTrace();
                }
            });
            f = OldHyrDataServiceImpl.exit(f, vernier, e);
        }
    }
    @Autowired
    private CustomerProductMapper customerProductMapper;
    private void bulidOrder(List<HXBXPolicyPO> bdbInSurePOS) {
        for (HXBXPolicyPO h : bdbInSurePOS) {
            CustomerProductInfoRo customerProductInfoRo = new CustomerProductInfoRo();
            customerProductInfoRo.setDatabaseName("baoxian");
            customerProductInfoRo.setTableName("sale_policy");
            String eventType = SyncTypeEnum.NEW.getValue();
            customerProductInfoRo.setSyncType(eventType);
            customerProductInfoRo.setSubSystemSign("BXHX");
            customerProductInfoRo.setSystemSign("BX");
            customerProductInfoRo.setProductSourceSystem("20");
            customerProductInfoRo.setProductStatus(CustomerProductInfoServiceImpl.getYZTStatus("BXHX" + h.getPolicyStatus()));
            customerProductInfoRo.setProductStartTime(h.getEffectiveDate());
            customerProductInfoRo.setProductEndTime(h.getPolicyValidityDate());
            if (customerProductInfoRo.getProductStartTime() != null && customerProductInfoRo.getProductEndTime() != null) {
                int deadLine = (int) ((customerProductInfoRo.getProductEndTime().getTime() - customerProductInfoRo.getProductStartTime().getTime()) / (1000 * 3600 * 24));
                customerProductInfoRo.setProductDeadline(deadLine + "");
            }
            customerProductInfoRo.setTableKey(h.getId() + "");

            String tbrId = h.getApplicantIdcard();
            String tbrType = h.getApplicantCardtype();
            String tbrName = h.getApplicantName();
            if (StringUtils.isNotBlank(tbrId)) {
                //查询投保人信息
                Example tbE = new Example(BxhxYztPO.class);
                Example.Criteria tbC = tbE.createCriteria();
                tbC.andEqualTo("cardid", tbrId);
                tbC.andEqualTo("cardType", tbrType);
                tbC.andEqualTo("name", tbrName);
                BxhxYztPO bxhxYztPO = null;
                try {
                    bxhxYztPO = yztSyncUserMapper.selectOneByExample(tbE);
                } catch (Exception e) {
                }
                if (bxhxYztPO != null && StringUtils.isNotBlank(bxhxYztPO.getCustomerNo())) {
                    customerProductInfoRo.setUserResourceId("BXHX" + bxhxYztPO.getCustomerNo());
                    customerProductInfoRo.setCustomerNo(bxhxYztPO.getCustomerNo());
                    //customerProductInfoRo.setCustomerRole("3");
                    //查产品保单关联表
                    Example policyProE = new Example(BXHXSalePolicyProPO.class);
                    Example.Criteria policyProC = policyProE.createCriteria();
                    policyProC.andEqualTo("policyId", h.getId());
                    List<BXHXSalePolicyProPO> bxhxSalePolicyProPOS = null;
                    try {
                        bxhxSalePolicyProPOS = salePolicyProMapper.selectByExample(policyProE);
                    } catch (Exception e) {
                    }

                    for (BXHXSalePolicyProPO b : bxhxSalePolicyProPOS) {
                        if (b.getDr() != 1) {
                            Integer pronum = b.getPronum();
                            if (pronum >= 1) {
                                customerProductInfoRo.setProductAmount(BigDecimal.valueOf(b.getScalePremium() / pronum));
                                customerProductInfoRo.setProductNo(b.getProId() + "");
                                for (int i = pronum; i > 0; i--) {
                                    customerProductInfoRo.setTableKey(b.getId() + "_" + i);
                                    syncDataService.syncCustomerProduct(customerProductInfoRo);
                                }
                            }
                        }
                    }

                    //保存银行卡信息
                    CustomerAccountInfoRo customerAccountInfoRo = new CustomerAccountInfoRo();
                    customerAccountInfoRo.setSyncType(eventType);
                    customerAccountInfoRo.setSubSystemSign("BXHX");
                    customerAccountInfoRo.setSystemSign("BX");

                    customerAccountInfoRo.setAccountNo(h.getBankAccount());
                    customerAccountInfoRo.setAccountType(CustomerConstants.CUSTOMER_ACCOUNT_TYPE_BANK_CARD);
                    customerAccountInfoRo.setUserSourceId(customerProductInfoRo.getUserResourceId());
                    customerAccountInfoRo.setCustomerNo(customerProductInfoRo.getCustomerNo());
                    customerAccountInfoRo.setAccountCreateTime(customerProductInfoRo.getProductStartTime());
                    customerAccountInfoRo.setAccountStatus(CustomerConstants.STATUS_ACCOUNT_AVAILABLE);
                    if (StringUtils.isNotBlank(customerAccountInfoRo.getCustomerNo()) && StringUtils.isNotBlank(customerAccountInfoRo.getAccountNo())) {
                        syncDataService.syncCustomerAccount(customerAccountInfoRo);
                    }
                    //保存被保人角色
                    String bbrId = h.getRecognizeeIdcard();
                    String bbrType = h.getRecognizeeCardtype();
                    String bbrName = h.getRecognizeeName();
                    if (StringUtils.isNotBlank(bbrId)) {
                        //查询被保人客户号
                        Example bbE = new Example(BxhxYztPO.class);
                        Example.Criteria bbC = bbE.createCriteria();
                        bbC.andEqualTo("cardid", bbrId);
                        bbC.andEqualTo("cardType", bbrType);
                        bbC.andEqualTo("name", bbrName);
                        BxhxYztPO bbr = null;
                        try {
                            bbr = yztSyncUserMapper.selectOneByExample(bbE);
                        } catch (Exception e) {
                        }
                        if (bbr != null && StringUtils.isNotBlank(bbr.getCustomerNo())) {
                            //增加被保人角色
                            syncDataService.addRoleInfo("BXHX" + bbr.getCustomerNo(), bbr.getCustomerNo(), "BX", "BXHX", "4", CustomerConstants.CUSTOMER_ROLE_EFFECTIVE);

                            //保存关系信息
                            CustomerRelationInfoPo customerRelationInfoPo = new CustomerRelationInfoPo();
                            customerRelationInfoPo.setRelationId("tbBXHX" + bxhxYztPO.getCustomerNo() + "bbBXHX" + bbr.getCustomerNo());
                            customerRelationInfoPo.setCustomerNo(bxhxYztPO.getCustomerNo());
                            customerRelationInfoPo.setRoleInRelation(2);
                            CustomerRelationInfoPo customerRelationInfoPo1 = customerRelationInfoMapper.selectOne(customerRelationInfoPo);
                            if (customerRelationInfoPo1 == null) {
                                customerRelationInfoPo.setId(UUIDUtils.getUUID());
                                customerRelationInfoPo.setCreateTime(new Timestamp(System.currentTimeMillis()));
                                customerRelationInfoPo.setSubSystemSign("BXHX");
                                customerRelationInfoPo.setSystemSign("BX");
                                customerRelationInfoPo.setRelationId("tbBXHX" + bxhxYztPO.getCustomerNo() + "bbBXHX" + bbr.getCustomerNo());
                                customerRelationInfoPo.setRelationSource(2);
                                customerRelationInfoPo.setRoleInRelation(2);
                                try {
                                    customerRelationInfoMapper.insert(customerRelationInfoPo);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                            customerRelationInfoPo.setRoleInRelation(3);
                            customerRelationInfoPo.setCustomerNo(bbr.getCustomerNo());
                            CustomerRelationInfoPo customerRelationInfoPo2 = customerRelationInfoMapper.selectOne(customerRelationInfoPo);
                            if (customerRelationInfoPo2 == null) {
                                customerRelationInfoPo.setId(UUIDUtils.getUUID());
                                customerRelationInfoPo.setCreateTime(new Timestamp(System.currentTimeMillis()));
                                customerRelationInfoPo.setSubSystemSign("BXHX");
                                customerRelationInfoPo.setSystemSign("BX");
                                customerRelationInfoPo.setRelationId("tbBXHX" + bxhxYztPO.getCustomerNo() + "bbBXHX" + bbr.getCustomerNo());
                                customerRelationInfoPo.setRelationSource(2);
                                customerRelationInfoPo.setRoleInRelation(3);
                                customerRelationInfoMapper.insert(customerRelationInfoPo);
                            }
                        }
                    }
                }
            }
        }
    }
}
